package com.ykc.helper;

import com.ykc.spring.*;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.ArrayUtils;

import java.lang.reflect.Field;
import java.util.*;

public class IOCHelper {
    static {
        Map<String,List<Object>> beanMap=BeanHelper.getBeanMap();
        if (MapUtils.isNotEmpty(beanMap)){
            for (Map.Entry<String,List<Object>> entry:beanMap.entrySet()){
                //获取类名与类实例
                List<Object> clsInfo = entry.getValue();
                //clsInfo的value的0索引对应的是该bean的BeanDefinition，1索引对应的是该bean的实例
                Class<?> cls= ((BeanDefinition) clsInfo.get(0)).getBeanClass();
                Object beanInstance=clsInfo.get(1);

                //
                Field[] beanFields=cls.getDeclaredFields();
                if (ArrayUtils.isNotEmpty(beanFields)) {
                    for (Field beanField:beanFields){
                        //如果字段是被AutoWired注解
                        if (beanField.isAnnotationPresent(AutoWired.class)){
                            //属性名
//                            String tmp=beanField.getName();
//                            String beanFieldName=tmp.substring(tmp.lastIndexOf(".")+1);
                            String beanFieldName=getBeanName(beanField.getType(),beanMap);
                            //获取Class类对应的实例
                            Object beanFieldInstance = beanMap.get(beanFieldName).get(1);
                            if (beanFieldInstance != null) {
                                beanField.setAccessible(true); //去除私有权限
                                try {
                                    beanField.set(beanInstance, beanFieldInstance);
                                } catch (IllegalAccessException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    public static String getBeanName(Class<?> cls,Map<String,List<Object>> beanMap){
        for (Map.Entry<String,List<Object>> entry:beanMap.entrySet()){
            BeanDefinition beanDefinition=(BeanDefinition)entry.getValue().get(0);
            if (beanDefinition.getBeanClass().equals(cls)){
                return entry.getKey();
            }
        }
        return "";
    }
}
